import React, {Fragment, PureComponent, useContext, useEffect, useRef, useState} from 'react';
import {
    Alert,
    Modal,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
} from "react-native";
const ModalContext = React.createContext();

class CustomModal extends PureComponent{

    constructor(props) {
        super(props);
        this.state = {
            show:false,
            content: <></>,
        }
        this.showContent = this.showContent.bind(this)
        this.close = this.close.bind(this)
    }

    showContent(content){
        this.setState({
            content: content,
            show:true
        })
    }
    close(){
        this.setState({
            show:false,
            content: <></>,
        })
    }

    render(){


        return (
            <Modal
                animationType="slide"
                transparent={true}
                visible={this.state.show}
                onRequestClose={() => {
                    this.close()
                }}
            >
                <View style={{flex:1,justifyContent:'flex-end'}}>
                    <View style={[StyleSheet.absoluteFill,{backgroundColor:'rgba(0,0,0,0.55)'}]}/>

                    {this.state.content}

                </View>
            </Modal>
        );
    }
}


export function useModal(){
    const context = useContext(ModalContext)
    const showContent = (content)=>{
        context.showContent(content)
    }
    const close = ()=>{
        context.close()
    }
    return {
        showContent,close
    }
}

export function DefaultModal(props){
    const ref = useRef({});
    const forceUpdate = useState()[1];
    useEffect(
        () => {
            forceUpdate({});
        },
        [ref.current]
    );

    return (
        <Fragment>
            <ModalContext.Provider value={ref.current}>{props.children}</ModalContext.Provider>
            <CustomModal ref={ref} />
        </Fragment>
    );
}

const styles = StyleSheet.create({
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 22
    },
    modalView: {
        margin: 20,
        backgroundColor: "white",
        borderRadius: 20,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    openButton: {
        backgroundColor: "#F194FF",
        borderRadius: 20,
        padding: 10,
        elevation: 2
    },
    textStyle: {
        color: "white",
        fontWeight: "bold",
        textAlign: "center"
    },
    modalText: {
        marginBottom: 15,
        textAlign: "center"
    }
});

